var WebSocketManager = (function () {
    var instance = null;
    var connection = null;
    var heartbeatTimer = null;
    var messageQueue = [];
    var reconnectAttempts = 0;
    var maxReconnectAttempts = 5;
    const MASTER_PAGE_KEY = 'ws_master_page';

    // 增加配置对象以支持自定义心跳内容
    var config = {
        heartbeat: {
            enable: true,
            interval: 30000,
            message: ()=>({}) // 默认心跳内容，可自定义
        }
    };

    // 私有方法
    function init(url) {
        return {
            connect: function (url, successCallback) {
                if (instance && connection) {
                    return;
                }

                if (!window.WebSocket) {
                    console.error("浏览器不支持websocket");
                    return;
                }

                connection = new WebSocket(url);

                // 连接成功处理
                connection.onopen = function (event) {
                    console.log('WebSocket连接成功');
                    reconnectAttempts = 0;

                    // 主页面竞争
                    this.checkMasterPage();

                    // 处理消息队列
                    messageQueue.forEach(msg => this.send(msg));
                    messageQueue = [];

                    // 连接成功后启动心跳
                    if (config.heartbeat.enable) {
                        this.startHeartbeat();
                    }

                    if (typeof successCallback === 'function') {
                        successCallback(event);
                    }
                }.bind(this);

                // 消息接收处理
                connection.onmessage = function (evt) {
                    try {
                        const data = JSON.parse(evt.data);
                        if (this.onDataCallback) {
                            this.onDataCallback(data);
                        }
                    } catch (error) {
                        console.error('消息解析失败:', error);
                    }
                }.bind(this);

                // 连接关闭处理
                connection.onclose = (event) =>  {
                    console.log('WebSocket连接断开');
                    this.closeHeartbeat();

                    // 自动重连
                    if (reconnectAttempts < maxReconnectAttempts) {
                        setTimeout(() => {
                            reconnectAttempts++;
                            console.log(`尝试第${reconnectAttempts}次重连...`);
                            this.connect(url);
                        }, 3000);
                    }
                };

                // 错误处理
                connection.onerror = function (error) {
                    console.error('WebSocket错误:', error);
                };

            },

            // 主页面竞争逻辑
            checkMasterPage: function () {
                const currentPageId = String(this.pageId);
                const masterPageId = Store.get(MASTER_PAGE_KEY);

                if (!masterPageId || masterPageId === 'null') {
                    // 成为主页面
                    Store.set(MASTER_PAGE_KEY, currentPageId);
                    console.log(`[Master Page] ${currentPageId} 成为主页面`);
                    window.addEventListener('beforeunload', () => {
                        if (Store.get(MASTER_PAGE_KEY) === currentPageId) {
                            Store.remove(MASTER_PAGE_KEY);
                        }
                    });
                }
            },

            send: function (message) {
                const packet = JSON.stringify(message);
                if (connection && connection.readyState === WebSocket.OPEN) {
                    connection.send(packet);
                } else {
                    console.warn('连接未就绪，消息进入队列');
                    if (messageQueue.length < 100) {
                        messageQueue.push(packet);
                    } else {
                        console.error('消息队列已满');
                    }
                }
            },

            onData: function (callback) {
                this.onDataCallback = callback;
            },

            close: function () {
                if (connection) {
                    connection.close();
                    console.log("主动关闭WebSocket连接");
                }
            },

            startHeartbeat: function () {
                const isMaster = Store.get(MASTER_PAGE_KEY) === String(this.pageId);
                if (isMaster && !heartbeatTimer) {
                    console.log('[Heartbeat] 主页面开始发送心跳');

                    // 动态生成心跳消息
                    const generateHeartbeatMessage = () => {
                        return typeof config.heartbeat.message === 'function'
                            ? config.heartbeat.message()
                            : config.heartbeat.message;
                    };
                    const send = () => {
                        if (connection.readyState === WebSocket.OPEN) {
                            const msg = generateHeartbeatMessage();
                            console.log('[Heartbeat] 发送:', msg);
                            this.send(msg);
                        }
                    };
                    send();
                    // 启动定时器
                    heartbeatTimer = setInterval(send, config.heartbeat.interval);
                }
            },

            closeHeartbeat: function () {
                if (heartbeatTimer) {
                    console.log('[Heartbeat] 停止心跳');
                    clearInterval(heartbeatTimer);
                    heartbeatTimer = null;
                }
            }
        };
    }

    return {
        getInstance: function (url, options = {}, successCallback) {
            if (!instance) {
                // 深度合并配置
                config = {
                    ...config,
                    ...options,
                    heartbeat: {
                        ...config.heartbeat,
                        ...(options.heartbeat || {}),
                        message: options.heartbeat?.message || config.heartbeat.message
                    }
                };
                instance = init(url);
                instance.pageId = Date.now(); // 生成唯一页面标识
                instance.connect(url, successCallback);
            }
            return instance;
        }
    };
})();